<template>
  <div class="login" :style="'background-image:url(' + tenantInfo.backgroundPicture + ')'">

    <div :class="`star${index}`" v-for="index in 6" :key="index"></div>

    <div class="square" v-for="index in 10" :key="index" :style="`--i: ${index - 1}`"></div>
    <div class="login-box">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">{{ tenantInfo.companyName || '' }}</h3>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="密码登陆" name="code">
            <span v-if="activeName === 'code'">
              <el-form-item v-if="tenantShow" prop="tenantId">
                <el-select v-model="loginForm.tenantId" filterable placeholder="请选择/输入公司名称" style="width: 100%">
                  <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName"
                    :value="item.tenantId"></el-option>
                  <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
                </el-select>
              </el-form-item>
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
                  <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
                  @keyup.enter="handleLogin">
                  <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
                </el-input>
              </el-form-item>
              <el-form-item v-if="captchaEnabled" prop="code">
                <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%"
                  @keyup.enter="handleLogin">
                  <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" class="login-code-img" @click="getCode" />
                </div>
              </el-form-item>
              <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>
              <el-form-item style="float: right">
            <el-button circle title="微信登录" @click="doSocialLogin('wechat_open')">
              <svg-icon icon-class="wechat" />
            </el-button>
            <!-- <el-button circle title="QQ登录" @click="doSocialLogin('qq')">
              <svg-icon icon-class="qq" />
            </el-button> -->
          </el-form-item>
            </span>
          </el-tab-pane>
          <el-tab-pane label="短信登陆" name="yzm">
            <span v-if="activeName === 'yzm'">

              <el-form-item prop="phonenumber">
                <el-input v-model="loginForm.phonenumber" type="text" size="large" auto-complete="off"
                  placeholder="手机号">
                  <template #prefix><el-icon>
                      <Iphone />
                    </el-icon></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="smsCode">
                <el-input v-model="loginForm.smsCode" size="large" auto-complete="off" placeholder="验证码"
                  @keyup.enter="handleLogin">
                  <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
                  <template #append>
                    <el-button type="primary" size="small" @click="handelSmsCaptcha">
                      <span v-if="!smsState" class="active">获取验证码</span>
                      <span v-else class="un-active">重新发送({{ times }})秒</span>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </span>
          </el-tab-pane>
        </el-tabs>
        <el-form-item style="width: 100%">
          <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin"
            v-if="activeName === 'code'">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <el-button v-else :loading="loading" size="large" type="primary" style="width: 100%"
            @click.prevent="handleLoginByCode">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div v-if="register" style="float: right">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--  凌创版权  -->
    <!-- <div class="el-login-footer">
      <span>Copyright © 2018-2024 福建凌创数字科技有限公司 All Rights Reserved.</span>
      <span><a target="_blank" href="http://beian.miit.gov.cn/">工业和信息化部 闽ICP备2024061190号-1</a></span>
    </div> -->
    <!--  金掌柜版权  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 福建金掌柜软件科技有限公司 All Rights Reserved.</span>
      <span><a target="_blank" href="http://beian.miit.gov.cn/">工业和信息化部 闽ICP备2023022614号-2</a></span>
      <span><img src="https://beian.mps.gov.cn/img/logo01.dd7ff50e.png" width="20" height="20"></img><a target="_blank"
          href="https://beian.mps.gov.cn/?spm=a21bo.jianhua/a.1997523009-ft.9.5af92a89mmSY8g#/query/webSearch/">闽公网安备35010302000835号</a></span>

    </div>
  </div>
</template>
<script setup lang="ts">
import { getCodeImg, getTenantList, getSMSCode, getTenantByDomain } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import * as Verify from '@/utils/verify'
import loginImg from '@/assets/images/login-background.jpg';

const userStore = useUserStore();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loginForm = ref<LoginData>({
  tenantId: '',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
  phonenumber: '',
  smsCode: '',
  terminal: 2
} as LoginData);
const activeName = ref('code');
const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
  phonenumber: [{ required: true, trigger: 'change', message: '请输入正确的手机号码' }],
  smsCode: [{ required: true, trigger: 'change', message: '请输入验证码' }],
};

const codeUrl = ref(true);
const loading = ref(false);
const defTimes = ref(60)
const times = ref(60)
const smsState = ref(false) //是否倒计时状态
const isLoading = ref(false) //是否正在发送短信验证码
const tenantInfo = ref({
  backgroundPicture: '',
  companyName: '金掌柜'
});
// 验证码开关
const captchaEnabled = ref(false);
// 租户开关
const tenantEnabled = ref(true);
const tenantShow = ref(false);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);
watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);


const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      console.log(loginForm.value);
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

const handleLoginByCode = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      const params = {
        phonenumber: loginForm.value.phonenumber,
        smsCode: loginForm.value.smsCode,
        grantType: 'sms',
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(params));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe),
    terminal: 2
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

// 点击发送短信验证码
const handelSmsCaptcha = () => {
  if (!isLoading.value && !smsState.value && loginRef.value?.validateField(['phonenumber']) && formValidation('GET_CAPTCHA')) {
    sendSmsCaptcha()
  }
}

// 表单验证
const formValidation = (scene = 'GET_CAPTCHA') => {
  // 验证获取短信验证码
  if (scene === 'GET_CAPTCHA') {
    if (!validteMobile(loginForm.value.phonenumber)) {
      return false
    }
  }
  // 验证提交登录
  if (scene === 'SUBMIT_LOGIN') {
    if (!validteMobile(loginForm.value.phonenumber) || !validteSmsCode(loginForm.value.smsCode)) {
      return false
    }
  }
  return true
}
// 请求发送短信验证码接口
const sendSmsCaptcha = () => {
  isLoading.value = true
  timer()
  getSMSCode({
    phonenumber: loginForm.value.phonenumber
  })
    .then(result => {
      console.log(result);
    })
    .catch(() => { })
    .finally(() => isLoading.value = false)
}

// 执行定时器
const timer = () => {
  smsState.value = true
  const inter = setInterval(() => {
    times.value = times.value - 1
    if (times.value <= 0) {
      smsState.value = false
      times.value = defTimes.value
      clearInterval(inter)
    }
  }, 1000)
}
// 验证手机号
const validteMobile = (str) => {
  if (Verify.isEmpty(str)) {
    proxy.$modal.msgError('请先输入手机号')
    return false
  }
  if (!Verify.isMobile(str)) {
    proxy.$modal.msgError('请输入正确格式的手机号')
    return false
  }
  return true
}
// 验证短信验证码
const validteSmsCode = (str) => {
  if (Verify.isEmpty(str)) {
    proxy.$modal.msgError('请先输入短信验证码')
    return false
  }
  return true
}
//检测租户选择框的变化
watch(
  () => loginForm.value.tenantId,
  () => {
    localStorage.setItem('tenantId', String(loginForm.value.tenantId));
  }
);

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
// 根据域名获取租户信息
const getTenantInfo = async () => {
  const { data } = await getTenantByDomain(location.host);
  tenantInfo.value = data || {
    backgroundPicture: loginImg,
    companyName: '金掌柜'
  };
  loginForm.value.tenantId = data?.tenantId || '000000';
  if (import.meta.env.MODE === 'production') {
    tenantShow.value = false;
  } else {
    tenantShow.value = true;
  }
};
onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
  getTenantInfo();
});
</script>

<style lang="scss" scoped>
@keyframes loginline {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 100;
  position: relative;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-box {
  z-index: 100;
  position: relative;
  overflow: hidden;
  width: 404px;
  padding: 2px;
  border-radius: 10px;

  &::before,
  &::after {
    content: "";
    position: absolute;
    top: -50%;
    left: -50%;
    z-index: 0;
    width: 404px;
    height: 440px;
    background: linear-gradient(0deg, transparent, transparent, #4b3bf9, #4b3bf9, #4b3bf9);
    transform-origin: bottom right;
    animation: loginline 5s linear infinite;
  }

  &::after {
    background: linear-gradient(0deg, transparent, transparent, #ff2771, #ff2771, #ff2771);
    animation-delay: -3s;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

.active {
  color: #409EFF;
}

.un-active {
  color: #c0c4cc;
}

@function getShadows($n) {
  $shadows: "#{random(100)}vw #{random(100)}vh #fff";

  @for $i from 2 through $n {
    $shadows: "#{$shadows},#{random(100)}vw #{random(100)}vh #fff";
  }

  @return unquote($shadows);
}

@keyframes moveUp {
  100% {
    transform: translateY(-100vh);
  }
}

$duration: 600s;
$count: 1400;

@for $i from 1 through 6 {
  $duration: floor(calc($duration / 2));
  $count: floor(calc($count / 2));

  .star#{$i} {
    $size: #{$i}px;
    position: fixed;
    top: 0;
    left: 0;
    width: $size;
    height: $size;
    border-radius: 50%;
    box-shadow: getShadows($count);
    animation: moveUp $duration linear infinite;

    &::after {
      position: fixed;
      top: 100vh;
      left: 0;
      width: $size;
      height: $size;
      content: "";
      border-radius: inherit;
      box-shadow: inherit;
    }
  }
}
</style>
<style type="text/css">
.login .el-tabs__nav-wrap:after {
  display: none;
}
</style>
